<?php
// 设置响应头
header('Content-Type: application/json');

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => '只允许POST请求']);
    exit;
}

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// 验证数据
$imageData = $data['imageData'] ?? '';
$textContentSource = $data['textContentSource'] ?? '';
$customPrompt = $data['customPrompt'] ?? '';
$systemPrompt = $data['systemPrompt'] ?? '';

if (empty($imageData) && empty($textContentSource)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => '请提供图片URL或文本内容']);
    exit;
}

// 检查系统变量
$modelscopeToken = getenv('MODELSCOPE_SDK_TOKEN');
if ($modelscopeToken === false || empty(trim($modelscopeToken))) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => '系统变量 MODELSCOPE_SDK_TOKEN 未配置']);
    exit;
}

// 处理图片数据
$imageUrl = $imageData;
if (strpos($imageData, 'data:image') === 0) {
    // 如果是base64图片，需要先保存为临时文件
    $imageData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $imageData));
    if ($imageData === false) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => '无效的图片数据']);
        exit;
    }

    // 创建临时文件
    $tempFile = tempnam(sys_get_temp_dir(), 'modelscope_img_');
    file_put_contents($tempFile, $imageData);

    // 这里需要将临时文件转换为可访问的URL
    // 由于环境限制，我们暂时不支持base64图片上传到ModelScope
    unlink($tempFile);

    echo json_encode([
        'success' => false,
        'message' => 'ModelScope API暂时不支持base64图片，请使用图片URL'
    ]);
    exit;
}

// 根据是否有图片选择不同的模型
$model = $imageData ? 'Qwen/Qwen3-VL-235B-A22B-Instruct' : 'MiniMax/MiniMax-M2';

// 构建消息
$messages = [];

if ($imageData) {
    // 有图片的情况 - 使用VLM模型
    $content = [];

    // 添加文本内容
    $textContent = '';
    if ($textContentSource) {
        $textContent .= $textContentSource . "\n\n";
    }
    if ($customPrompt) {
        $textContent .= $customPrompt . "\n\n";
    }
    $textContent .= $systemPrompt;

    $content[] = [
        'type' => 'text',
        'text' => $textContent
    ];

    // 添加图片
    $content[] = [
        'type' => 'image_url',
        'image_url' => [
            'url' => $imageData
        ]
    ];

    $messages[] = [
        'role' => 'user',
        'content' => $content
    ];
} else {
    // 没有图片的情况 - 使用LLM模型
    $messages[] = [
        'role' => 'system',
        'content' => $systemPrompt
    ];

    $userContent = $textContentSource;
    if ($customPrompt) {
        $userContent .= ($userContent ? "\n\n" : '') . $customPrompt;
    }

    $messages[] = [
        'role' => 'user',
        'content' => $userContent ?: '请分析提供的内容并生成FAQ。'
    ];
}

// 调用ModelScope API
$ch = curl_init();

$apiUrl = 'https://api-inference.modelscope.cn/v1/chat/completions';

$requestData = [
    'model' => $model,
    'messages' => $messages,
    'stream' => false
];

curl_setopt_array($ch, [
    CURLOPT_URL => $apiUrl,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($requestData),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . trim($modelscopeToken)
    ],
    CURLOPT_TIMEOUT => 60,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_USERAGENT => 'ModelScope-PHP-Client'
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($response === false || !empty($error)) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'API调用失败: ' . $error
    ]);
    exit;
}

if ($httpCode !== 200) {
    http_response_code($httpCode);
    echo json_encode([
        'success' => false,
        'message' => 'API返回错误状态码: ' . $httpCode,
        'response' => $response
    ]);
    exit;
}

$result = json_decode($response, true);
if ($result === null) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'API响应解析失败',
        'response' => $response
    ]);
    exit;
}

if (!isset($result['choices'][0]['message']['content'])) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'API响应格式异常',
        'response' => $result
    ]);
    exit;
}

$content = $result['choices'][0]['message']['content'];

echo json_encode([
    'success' => true,
    'content' => $content,
    'usage' => $result['usage'] ?? null
]);
?>
